package com.example.wenhua.service.impl;

import com.example.wenhua.entity.User;
import com.example.wenhua.mapper.UserMapper;
import com.example.wenhua.service.UserService;
import com.example.wenhua.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.List;

/**
 * 用户业务逻辑实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    @Override
    public List<User> getAllUsers() {
        return userMapper.findAll();
    }
    
    @Override
    public User getUserByHm(String hm) {
        return userMapper.findByHm(hm);
    }
    
    @Override
    public List<User> getUsersByRole(Integer role) {
        return userMapper.findByRole(role);
    }
    
    @Override
    @Transactional
    public boolean addUser(User user) {
        // 检查用户名是否已存在
        if (userMapper.findByHm(user.getHm()) != null) {
            throw new RuntimeException("用户名已存在：" + user.getHm());
        }
        
        // 加密密码
        user.setPwd(encryptPassword(user.getPwd()));
        
        return userMapper.insert(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean updateUser(User user) {
        // 如果密码不为空，则加密
        if (user.getPwd() != null && !user.getPwd().isEmpty()) {
            user.setPwd(encryptPassword(user.getPwd()));
        }
        
        return userMapper.update(user) > 0;
    }
    
    @Override
    @Transactional
    public boolean deleteUser(String hm) {
        return userMapper.delete(hm) > 0;
    }
    
    @Override
    public User login(String hm, String pwd) {
        // 加密输入的密码
        String encryptedPwd = encryptPassword(pwd);
        
        // 验证登录
        User user = userMapper.validateLogin(hm, encryptedPwd);
        
        if (user != null) {
            // 清除密码信息，不返回给前端
            user.setPwd(null);
        }
        
        return user;
    }
    
    @Override
    @Transactional
    public boolean changePassword(String hm, String oldPwd, String newPwd) {
        // 验证旧密码
        User user = userMapper.findByHm(hm);
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        if (!verifyPassword(oldPwd, user.getPwd())) {
            throw new RuntimeException("原密码错误");
        }
        
        // 更新密码
        String encryptedNewPwd = encryptPassword(newPwd);
        return userMapper.updatePassword(hm, encryptedNewPwd) > 0;
    }
    
    @Override
    @Transactional
    public boolean resetPassword(String hm, String newPwd) {
        // 检查用户是否存在
        if (userMapper.findByHm(hm) == null) {
            throw new RuntimeException("用户不存在");
        }
        
        // 重置密码
        String encryptedNewPwd = encryptPassword(newPwd);
        return userMapper.updatePassword(hm, encryptedNewPwd) > 0;
    }
    
    @Override
    public String encryptPassword(String password) {
        // 使用MD5加密，添加盐值
        String salt = "wenhua_salt";
        return DigestUtils.md5DigestAsHex((password + salt).getBytes());
    }
    
    @Override
    public boolean verifyPassword(String password, String encryptedPassword) {
        return encryptPassword(password).equals(encryptedPassword);
    }
    
    @Override
    public String loginWithToken(String hm, String pwd) {
        // 验证用户登录
        User user = login(hm, pwd);
        if (user == null) {
            return null;
        }
        
        // 生成JWT token
        return jwtUtil.generateToken(user.getHm(), user.getRole());
    }
    
    @Override
    public boolean hasPermission(String username, Integer requiredRole) {
        User user = getUserByHm(username);
        if (user == null) {
            return false;
        }
        
        // 角色权限检查：管理员(0) > 教师(1) > 学生(2)
        // 数字越小权限越高
        return user.getRole() <= requiredRole;
    }
    
    @Override
    public String refreshToken(String token) {
        return jwtUtil.refreshToken(token);
    }
}